# Python 趣味编程：第 2 章　
# 练习问题 2.1 启动“车”
# 错误的例子
# --------------------------
# 程序名: ex02-1-cars-err.py

from tkinter import *
from dataclasses import dataclass
import time

# 初始数据
DURATION = 0.01    # sleep时间=绘图的间隔
steps = 20000      # 帧数
RIGHT = 700        # 右侧的“折回”位置
LEFT = 100         # 左侧的“折回”位置

@dataclass
class Car:
    x: int
    y: int
    l: int
    h: int
    wr: int
    vx: int
    c: str

# 生成单独的汽车。把“词典”还给你。
def create_car(x, y, l, h, wr, bcolor):
    canvas.create_rectangle(x, y, x + l, y + h,
                            fill=bcolor, outline=bcolor)
    wh_1_x = x + l/4 - wr      # 前轮的中心位于整体的1/4位置
    wh_2_x = x + 3*l/4 - wr  # 后轮的中心位于整体的3/4的位置
    wh_y = y + h - wr
    canvas.create_oval(wh_1_x, wh_y, wh_1_x + 2*wr,  wh_y + 2*wr,
                       fill="black", outline="black")
    canvas.create_oval(wh_2_x, wh_y, wh_2_x + 2*wr, wh_y + 2*wr,
                       fill="black", outline="black")

tk=Tk()
canvas = Canvas(tk, width=800, height=600, bd=0)
canvas.pack()
tk.update()

# 汽车数据
cars = [
    Car(150, 100, 100, 50, 10, 1, "blue"),
    Car(200, 250, 100, 70, 5, 2, "red"),
    Car(250, 400, 200, 40, 10, 1, "orange")
    ]

# 整个程序的循环
for s in range(steps):
    for car in cars:      # 对所有的汽车重复
        # 左边是下一个穿墙的
        if (car.x + car.vx <= LEFT \
            or car.x + car.l >= RIGHT):   # 如果右边穿墙
            car.vx = -car.vx    # 翻转移动方向
        car.x = car.x + car.vx
        create_car(car.x, car.y, car.l, car.h, car.wr, car.c)
    tk.update()           # 绘图反映在画面上
    time.sleep(DURATION)  # 在接下来的绘图之前，都要sleep

